<?php

namespace App\Http\Controllers\Admin;

use App\Models\Admin\AdminMenu;
use App\Models\Admin\AdminUser;
use App\Models\Admin\Goods;
use App\Models\Admin\SalesStrategy;
use App\Models\Admin\GoodsStore;
use App\Models\Admin\Store;
use App\Models\Admin\SalesStrategyViewPermissions;
use App\Tools\AliSms;
use App\Tools\Financial;
use App\Tools\Images;
use App\Tools\Prstatic;
use App\Tools\Texcel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\DB;

class SalesStrategyViewPermissionsListController extends BaseController
{
    /**
     * 商户供应商列表
     */
    /**
     * 代理商商品权限列表
     */


    public function SalesStrategyViewPermissionsList()
    {
        $params = $this->requestArr;
        if (empty($params['store_id'])) {
            return redirect()->back()->withErrors('缺少 store_id 参数');
        }

        if (empty($params['type'])) {
            return redirect()->back()->withErrors('缺少 sales_type 参数');
        }

        $permission = SalesStrategyViewPermissions::where('store_id', $params['store_id'])->first();
        $allowedGoodsIds = $permission
            ? array_filter(explode(',', $permission->goods_ids), 'is_numeric')
            : [];

        $query = SalesStrategy::where('type', $params['type'])->select();

        if (!empty($allowedGoodsIds)) {
            $query->selectRaw('IF(id IN (' . implode(',', $allowedGoodsIds) . '), 1, 0) as has_permission');
        } else {
            $query->selectRaw('0 as has_permission');
        }

        // 添加筛选条件
//        if (!empty($params['goods_name'])) {
//            $query->where('goods_name', 'like', '%' . $params['goods_name'] . '%');
//        }
//        if (!empty($params['goods_sn'])) {
//            $query->where('goods_sn', $params['goods_sn']);
//        }
//        if (isset($params['has_permission']) && $params['has_permission'] !== '') {
//            $query->whereIn('id', $allowedGoodsIds, 'and', $params['has_permission'] == '1');
//        }

        $list = $query->paginate(10);
        foreach ($list as &$value) {
            $value['type_str'] = $value['type'] == 1 ? '金额满赠' : '单品满赠';
            $value['status'] = $value['end'] > time() ? '正常' : '已失效';
            $value['start'] = date("Y-m-d H:i:s", $value['start']);
            $value['end'] = date("Y-m-d H:i:s", $value['end']);
            if ($value['type'] == 2) {
                $info = Goods::getInfo(['id' => $value['goods_id']]);
            }
            $value['note'] = $value['type'] == 1 ? '金额满' . $value['amount'] . '元' : '单品【' . $info['goods_name'] . '】满' . $value['goods_number'] . '件';
        }
        if (!empty($where['start'])) {
            $list->appends(['start' => $where['start']])->render();
        }
        if (!empty($where['end'])) {
            $list->appends(['end' => $where['end']])->render();
        }
        $list->appends(['store_id' => $params['store_id']]);
        return view('admin.sales.salesStrategyViewPermissionsList', [
            'data' => $list,
            'params' => $params
        ]);
    }

    public function updateSalesPermission()
    {
        $request = request();
        $storeId = $request->store_id;
        $goodsId = $request->goods_id;
        $status = $request->status;
        $permission = SalesStrategyViewPermissions::where('store_id', $storeId)->first();
        if (!$permission) {
            $permission = new SalesStrategyViewPermissions();
            $permission->store_id = $storeId;
            $permission->goods_ids = '';
            $permission->store_name = ''; // 需要设置正确的店铺名
        }

        $goodsIds = explode(',', $permission->goods_ids);

        if ($status) {
            // 添加权限
            if (!in_array($goodsId, $goodsIds)) {
                $goodsIds[] = $goodsId;
            }
        } else {
            // 取消权限
            $goodsIds = array_diff($goodsIds, [$goodsId]);
        }

        $permission->goods_ids = implode(',', array_filter($goodsIds));
        $permission->save();
        return response()->json([
            'code' => 1,
            'msg' => '操作成功'
        ]);
    }


    /**s
     * 批量取消权限
     */
    public function batchRevokeSalesPermission()
    {
        $request = request();
        $storeId = $request->store_id;
        $type = $request->type; // 'page' 或 'all'
        $sales_type = $request->sales_type;
        $goodsIds = $request->goods_ids ?: [];
        // 使用 firstOrNew 避免重复查询
        $permission = SalesStrategyViewPermissions::firstOrNew(['store_id' => $storeId]);

        if (!$permission->exists) {
            $permission->store_name = Store::where('id', $storeId)->value('store_name') ?? '';
        }

        $currentGoodsIds = $permission->goods_ids ? explode(',', $permission->goods_ids) : [];

        if ($type === 'all') {
            // 获取所有有效商品ID
            $allGoodsIds = SalesStrategy::where('type', $sales_type)->pluck('id')->toArray();
            $newGoodsIds = array_values(array_diff($currentGoodsIds, $allGoodsIds));
        } else {
            $newGoodsIds = array_unique(array_merge($currentGoodsIds, $goodsIds));
        }


        $permission->goods_ids = implode(',', array_filter($newGoodsIds));
        $permission->save();

        return response()->json([
            'code' => 1,
            'msg' => '操作成功',
            'data' => [
                'revoked_count' => count($currentGoodsIds) - count($newGoodsIds)
            ]
        ]);
    }

    /**
     * 批量授予权限
     */
    public function batchGrantSalesPermission()
    {
        $request = request();
        $storeId = $request->store_id;
        $type = $request->type; // 'page' 或 'all'
        $sales_type = $request->sales_type;
        $goodsIds = $request->goods_ids ?: [];
        // 使用 firstOrNew 避免重复查询
        $permission = SalesStrategyViewPermissions::firstOrNew(['store_id' => $storeId]);

        if (!$permission->exists) {
            $permission->store_name = Store::where('id', $storeId)->value('store_name') ?? '';
        }

        $currentGoodsIds = $permission->goods_ids ? explode(',', $permission->goods_ids) : [];

        if ($type === 'all') {
            // 获取所有有效商品ID
            $allGoodsIds = SalesStrategy::where('type', $sales_type)->pluck('id')->toArray();
            $newGoodsIds = array_unique(array_merge($currentGoodsIds, $allGoodsIds));
        } else {
            $newGoodsIds = array_unique(array_merge($currentGoodsIds, $goodsIds));
        }

        $permission->goods_ids = implode(',', array_filter($newGoodsIds));
        $permission->save();

        return response()->json([
            'code' => 1,
            'msg' => '操作成功',
            'data' => [
                'granted_count' => count($newGoodsIds) - count($currentGoodsIds)
            ]
        ]);
    }

    /**
     * 获取分页列表
     */
    public static function getPageList($where = [], $limit = 10)
    {
        $permission = self::where('store_id', $where['store_id'])->first();
        $goodsIds = $permission ? explode(',', $permission->goods_ids) : [];

        // 获取所有有效商品
        $query = Goods::where("status", 1)
            ->select(['id as goods_id', 'cate_id', 'goods_name', 'goods_sn'])
            ->orderBy('id', 'desc');

        // 安全地添加权限标记
        if (!empty($goodsIds)) {
            $query->selectRaw('IF(id IN (' . implode(',', $goodsIds) . '), 1, 0) as has_permission');
        } else {
            $query->selectRaw('0 as has_permission');
        }

        // 添加筛选条件
        if (!empty($where['cate_id'])) {
            $query->where('cate_id', $where['cate_id']);
        }
        if (!empty($where['goods_name'])) {
            $query->where('goods_name', 'like', '%' . $where['goods_name'] . '%');
        }
        if (!empty($where['goods_sn'])) {
            $query->where('goods_sn', $where['goods_sn']);
        }
        if (!empty($where['has_permission'])) {
            $hasPermission = $where['has_permission'] == 1;
            $query->whereRaw('IF(id IN (' . implode(',', $goodsIds) . '), 1, 0) = ?', [$hasPermission ? 1 : 0]);
        }

        if ($limit == 0) {
            $goodsList = $query->get();
        } else {
            $goodsList = $query->paginate($limit);
        }

        // 添加店铺信息
        if ($permission && $goodsList) {
            $goodsList->store_name = $permission->store_name;
            $goodsList->store_id = $permission->store_id;
        }

        return $goodsList;
    }
}